package com.wuliming.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.wuliming.gulimall.search.config.EsConfig;
import com.wuliming.gulimall.search.constant.EsIndexConstant;
import com.wuliming.gulimall.search.service.SearchSaveService;
import com.wuliming.to.es.SkuEsModel;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class SearchSaveServiceImpl implements SearchSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean saveProduct(List<SkuEsModel> list) throws IOException {
        BulkRequest bulkRequest = new BulkRequest(EsIndexConstant.proudct);
        list.forEach(w->{
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(w.getSkuId().toString());
            indexRequest.source(JSON.toJSON(w), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, EsConfig.COMMON_OPTIONS);
        return !bulk.hasFailures();
    }
}
